package core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.UserInfo;

public class Main {

	private static String userName = "root";
	private static String password = "chaima8";

	public static void main(String[] args) {

		Connection conn = null;

		try {
			while (true) {
				String url = "jdbc:mysql://localhost/fbevents";

				Class.forName("com.mysql.jdbc.Driver").newInstance();

				conn = DriverManager.getConnection(url, userName, password);

				System.out.println("Database connection established");

				PreparedStatement query = conn
						.prepareStatement("select fb_user_name, "
								+ "fb_access_token, " + "fb_uid, "
								+ "google_user, " + "google_password "
								+ "from users");
				System.out.println("Trying to execute query");
				ResultSet results = query.executeQuery();
				System.out.println("Executed query with results "
						+ results.toString());
				while (results.next()) {
					String fbUserName = results.getString("fb_user_name");
					String fbAccessToken = results.getString("fb_access_token");
					String fbUserId = results.getString("fb_uid");
//					String authSubToken = results
//							.getString("google_access_token");
					String googleUserName = results.getString("google_user");
					String googlePassword = results.getString("google_password");
					UserInfo userInfo = new UserInfo(fbUserName, fbAccessToken, fbUserId, googleUserName, googlePassword);
					System.out.println(userInfo.toString());
					new GCalUpdate(userInfo).doUpdate();
				}
			}
		} catch (SQLException e) {
			System.err.println("Cannot connect to database server"
					+ e.getMessage());
			e.printStackTrace();
		}

		catch (Exception e) {
			System.err.println("Cannot connect to database server"
					+ e.toString());
		} finally {
			if (conn != null) {
				try {
					conn.close();
					System.out.println("Database connection terminated");
				} catch (Exception e) { /* ignore close errors */
				}
			}
		}
	}
}
